package lp.polimi.treefinder;

import java.io.IOException;

import lp.polimi.treefinder.utils.FilesUtils;
import lp.polimi.treefinder.utils.IntentUtils;
import lp.polimi.treefinder.utils.UIUtils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.widget.Toast;

public class SettingsFragment extends PreferenceFragment {


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.main_settings);

		Vibrator vib = (Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
		CheckBoxPreference vibratePref = (CheckBoxPreference) findPreference("vibrate");
		if (!vib.hasVibrator()) {
			vibratePref.setChecked(false);
			vibratePref.setEnabled(false);
		}

		if (!IntentUtils.hasFeature(getActivity(), PackageManager.FEATURE_CAMERA)) {
			Preference cameraPref = findPreference("start_with_camera");
			cameraPref.setEnabled(false);
		}


		Preference welcomePref = findPreference("welcome");
		welcomePref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			
			@Override
			public boolean onPreferenceClick(Preference preference) {
				UIUtils.showWelcomeDialog(getActivity());
				return true;
			}
		});

		Preference deleteTagsPref = findPreference("delete_tags");
		deleteTagsPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				new AlertDialog.Builder(getActivity()).setTitle(getResources().getString(R.string.delete_tags))
				.setMessage(getResources().getString(R.string.sure))
				.setPositiveButton(R.string.ok, new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							FilesUtils.deleteLeafTags(getActivity());
							Toast.makeText(getActivity(), R.string.toast_deleted_tags, Toast.LENGTH_LONG).show();
						} catch (IOException e) {
							new AlertDialog.Builder(getActivity()).setTitle(getResources().getString(R.string.error))
							.setMessage(getResources().getString(R.string.file_error))
							.setPositiveButton(R.string.ok, new OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									getActivity().finish();
								}
							}).show();
						}

					}
				})
				.setNegativeButton(R.string.cancel, null).show();
				return true;
			}
		});
	}
}



